import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 28463
 * Date: 2022—08—16
 * Time: 14:03
 */
public class JDBCSelect {
    public static void main(String[] args) throws SQLException {
        //1.创建数据源
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource)dataSource).setURL("jdbc:mysql://127.0.0.1:3306/java01?characterEncoding=utf8&useSSL=false");
        ((MysqlDataSource)dataSource).setUser("root");
        ((MysqlDataSource)dataSource).setPassword("111111");

        //2.和数据库建立连接
        Connection connection = dataSource.getConnection();

        //3.构造sql语句
/*        String sql = "select * from student1";
        PreparedStatement statement = connection.prepareStatement(sql);*/

        String sql = "select * from student1 where id = ?";
        PreparedStatement statement = connection.prepareStatement(sql);
        statement.setInt(1,2);

        //4.执行sql语句
        //查询语句要使用executeQuery来完成
        //返回结果是ResultSet，结果集，里面是一个“表”这样的数据结构
        ResultSet resultSet = statement.executeQuery();

        //5.遍历结果集合
        while (resultSet.next()) {
            //每次循环，都可以获取resultSet中的一行，进一步的就可以拿到每一列
            int id = resultSet.getInt("id");
            String name = resultSet.getString("name");
            System.out.println("id = " + id + ", name = " + name);
        }

        //6.释放资源
        resultSet.close();
        statement.close();
        connection.close();
    }
}
